package top.codedance.iotp.simulator.serialPort.listenner;

import top.codedance.iotp.common.util.BytesBuilder;
import top.codedance.iotp.simulator.serialPort.ComServer;
import top.codedance.iotp.simulator.serialPort.SimulatorApplication;
import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;
import org.apache.log4j.Logger;

import java.util.List;

public class SerialPortListener implements SerialPortDataListener {
    private Logger logger = SimulatorApplication.getLogger(SerialPortListener.class);

    private ComServer cs;
    private static BytesBuilder gbb = new BytesBuilder();

    public SerialPortListener(ComServer cs){
        this.cs = cs;
    }

    @Override
    public int getListeningEvents() {
        return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
    }

    public synchronized void serialEvent(SerialPortEvent serialPortEvent) {
        BytesBuilder bb = new BytesBuilder();
        SerialPort serialPort = serialPortEvent.getSerialPort();
        int avai = serialPort.bytesAvailable();
        while (avai != 0) {
            byte[] data = new byte[avai];
            serialPort.readBytes(data, avai);
            bb.append(data);
            avai = serialPort.bytesAvailable();
        }
        gbb.append(bb.toArray());
        byte[] data = gbb.toArray();
        logger.debug("receive: " + new String(data));
        try {
            List<BytesBuilder> results = SimulatorApplication.aimulator.exec(data);
            for (BytesBuilder bytesBuilder : results) {
                try {
                    byte[] bytes = bytesBuilder.toArray();
                    logger.debug("return: " + new String(bytes));
                    gbb = new BytesBuilder();
                    serialPort.writeBytes(bytes, bytes.length);
                } catch (Exception e) {
                    logger.debug(e.getMessage());
                }
            }
        } catch (Exception e){
            logger.debug(e.getMessage());
        } finally {
            gbb = new BytesBuilder();
        }
    }
}
